package com.chhuang.ewcrm.controller;

import com.chhuang.ewcrm.config.EwcrmProperties;
import com.chhuang.ewcrm.consts.EwcrmConstants;
import com.chhuang.ewcrm.entity.ECapturePic;
import com.chhuang.ewcrm.file.FileUtil;
import com.chhuang.ewcrm.service.ECapturePicService;
import com.chhuang.ewcrm.vo.ResultBean;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * (ECapturePic)表控制层
 *
 * @author chhuang
 * @since 2020-11-19 09:49:10
 */
@RestController
@RequestMapping("wapi/eCapturePic")
public class WCapturePicController {
    Logger logger = LoggerFactory.getLogger(WCapturePicController.class);
    /**
     * 服务对象
     */
    @Resource
    private ECapturePicService eCapturePicService;
    @Autowired
    private EwcrmProperties ewcrmProperties;

    /**
     * 上传抓拍的图片
     * @param weighId
     * @param capturePics
     * @return
     */
    @PostMapping("/upload")
    public ResultBean<?> uploadCapturePic(String weighId, MultipartFile[] capturePics) throws IOException {
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        if(StringUtils.isNotEmpty(weighId) && capturePics!=null && capturePics.length>0){
            List<ECapturePic> eCapturePicList = new LinkedList<>();
            for(MultipartFile pic : capturePics){
                if(pic!=null && !pic.isEmpty()){
                    ECapturePic eCapturePic = new ECapturePic();

                    String picname = pic.getOriginalFilename();//原文件名
                    String filePath = "CapturePic"+ File.separator+
                            weighId+File.separator+
                            picname;
                    String path = ewcrmProperties.getUploadPath()+filePath;

                    File file = new File(path);
                    FileUtil.makeFilePath(file);
                    pic.transferTo(file);

                    eCapturePic.setCapturePicPath(EwcrmConstants.UPLOAD_URL + path);
                    eCapturePic.setWeighId(weighId);
                    eCapturePic.setCreateTime(new Date());

                    eCapturePicList.add(eCapturePic);
                }
            }
            if(!eCapturePicList.isEmpty())
                eCapturePicService.insertBatch(eCapturePicList);

            resultBean.setSuccess(true);
        }else{
            resultBean.setMessage("参数不能为空");
        }

        return resultBean;
    }
}